<template>
  <div>
    <el-dialog
      :visible.sync="addDialogVisibleState"
      :title="'修改' + title"
      @open="getDataById"
    >
      <el-form :model="editData" :rules="formRules" ref="editParamsDialogForm">
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="editData.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <template slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="addProp">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ['sel', 'id'],
  computed: {
    addDialogVisibleState: {
      get() {
        return this.$store.state.params.editDialogVisible
      },
      set() {
        this.$store.commit('params/editDialogVisibleState', false)
      }
    },
    title() {
      return this.sel === 'many' ? '动态参数' : '静态属性'
    },
    // 通过vuex获得要编辑的数据的id,以获得数据
    attr_id() {
      return this.$store.state.params.editDataId
    }
  },
  data() {
    return {
      editData: {},
      formRules: {
        attr_name: [
          {
            required: true,
            message: '请输入动态参数/静态属性!',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async getDataById() {
      const { data: res } = await this.$http.get(
        `categories/${this.id}/attributes/${this.attr_id}`,
        { params: { attr_sel: this.sel } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取编辑数据失败！')
      }

      this.editData = res.data
    },
    addProp() {
      this.$refs.editParamsDialogForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请填写要添加的属性/参数')
        const { data: res } = await this.$http.put(
          `categories/${this.id}/attributes/${this.attr_id}`,
          {
            attr_name: this.editData.attr_name,
            attr_sel: this.sel,
            attr_vals: this.editData.attr_vals
          }
        )

        if (res.meta.status !== 200) return this.$message.error('添加失败！')
        this.$emit('updateList')
        this.closeDialog()
        return this.$message.success('添加成功！')
      })
    },
    closeDialog() {
      this.$store.commit('params/editDialogVisibleState', false)
      this.$refs.editParamsDialogForm.resetFields()
      this.editData.attr_name = ''
    }
  }
}
</script>

<style></style>
